package com.sk.mybatis.tools;

import org.apache.commons.lang3.StringUtils;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

/**
 * 获取数据库表信息
 */
public class MysqlInfoUtil {
    private String url;
    private String user;
    private String pwd;

    public MysqlInfoUtil() throws IOException {
        try {
            Properties properties = new Properties();
            properties.load(new FileInputStream("app.properties"));
            url = properties.getProperty("url");
            user = properties.getProperty("user");
            pwd = properties.getProperty("pwd");
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    /**
     * 生成数据库字段映射信息
     *
     * @param tableName 表明
     * @return
     * @throws ClassNotFoundException
     * @throws SQLException
     */
    public List<Column> getColumnMappingInfo(String tableName) throws ClassNotFoundException, SQLException {
        List<Column> list = new ArrayList<>();
        Class.forName("com.mysql.jdbc.Driver");
        try (Connection connection = DriverManager.getConnection(url, user, pwd)) {
            ResultSet rs = connection.getMetaData().getColumns(connection.getCatalog(), null, tableName, null);
            while (rs.next()) {
                list.add(new Column(rs.getString("COLUMN_NAME"), rs.getString("REMARKS"), rs.getString("TYPE_NAME")));
            }
        }
        return list;
    }


    public String underLineToCamelCase(String name) {
        name = name.toLowerCase();
        String[] split = name.split("_");
        for (int i = 0; i < split.length; i++) {
            split[i] = split[i].substring(0, 1).toUpperCase() + split[i].substring(1);
        }
        return StringUtils.join(Arrays.asList(split), "");
    }
}

